package com.fingard.dsp.bank.directbank.cmb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

/**
 * 招行单笔实时代扣
 *
 * @author Cruise
 * @date 2018年9月2日
 */
public class CMB01RealTime extends CMB01Base implements IRealTime {
    @Override
    public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;

        try {
            String tmpBUSCOD = "N03030";
            String tmpBUSMOD = getBankConfig().getMapValueByKey("busmod" + tmpBUSCOD, p_req9108.singleDetail.purpose);
            String tmpTrstypCode = getBankConfig().getMapValueByKey("ctrstypCode" + tmpBUSCOD, p_req9108.singleDetail.purpose);
            String tmpTrstypName = getBankConfig().getMapValueByKey("ctrstypName" + tmpBUSCOD, p_req9108.singleDetail.purpose);

            boolean isChecked = true;
            String tmpCheckMsg = "";
            if (StringHelper.isNullOrEmpty(tmpBUSMOD)) {
                isChecked = false;
                tmpCheckMsg = "未取到" + tmpBUSCOD + "的业务模式设置";
            }
            if (StringHelper.isNullOrEmpty(tmpTrstypCode)) {
                isChecked = false;
                tmpCheckMsg = "未取到" + tmpBUSCOD + "的交易代码设置";
            }
            if (StringHelper.isNullOrEmpty(tmpTrstypName)) {
                isChecked = false;
                tmpCheckMsg = tmpCheckMsg + "未取到" + tmpBUSCOD + "交易代码名称设置！";
            }
            if (!isChecked) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = tmpCheckMsg;
                tmpRetDetail.transState = PaymentState.FAIL_Payment;
                tmpRetDetail.payInfoCode = "E9981";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }

            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "AgentRequest";

            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, tmpBnkHeader);
            xmlWriter.writeStartElement("SDKATSRQX");
            xmlWriter.writeElementString("BUSCOD", tmpBUSCOD);
            xmlWriter.writeElementString("BUSMOD", tmpBUSMOD);
            xmlWriter.writeElementClosed("MODALS");
            xmlWriter.writeElementString("C_TRSTYP", tmpTrstypName);
            xmlWriter.writeElementString("TRSTYP", tmpTrstypCode);
            xmlWriter.writeElementClosed("EPTDAT");
            xmlWriter.writeElementString("DBTACC", p_req9108.singleDetail.recAct);
            xmlWriter.writeElementString("BBKNBR", p_req9108.singleDetail.recArea);
            xmlWriter.writeElementClosed("BANKAREA");
            xmlWriter.writeElementString("SUM", p_req9108.singleDetail.payAmount);
            xmlWriter.writeElementString("TOTAL", "1");
            xmlWriter.writeElementString("CCYNBR", convertCurToBank(p_req9108.singleDetail.recCur));
            xmlWriter.writeElementClosed("CURRENCY");
            xmlWriter.writeElementString("YURREF", p_req9108.singleDetail.askNumber);
            String bkMEMO = StringHelper.joinNotEmpty("-", p_req9108.singleDetail.abstractATS, p_req9108.singleDetail.purpose);
            bkMEMO = StringHelper.subStringByByte(bkMEMO, getCharset(), 42);
            xmlWriter.writeElementString("MEMO", bkMEMO);
            /*直连经办网银审批标志    为 Y 时必须使用有审批岗的模式；不为 Y 时，必须使用无审批岗的模式。*/
         /*   String grtFlag = getBankConfig().getValueAsString("grtFlag");
            if (grtFlag==null||"".equals(grtFlag)) {
                grtFlag = "N";
            }
            xmlWriter.writeElementString("GRTFLG", grtFlag);*/

            xmlWriter.writeEndElement();

            //需要进行对账码拼接以及节点解析，采用XElement进行处理
            XElement tmpXElement = new XElement("SDKATDRQX", "");
            tmpXElement.addChild(new XElement("ACCNBR", p_req9108.singleDetail.payAct));
            tmpXElement.addChild(new XElement("CLTNAM", p_req9108.singleDetail.payName));
            tmpXElement.addChild(new XElement("TRSAMT", p_req9108.singleDetail.payAmount));
            if (p_req9108.singleDetail.sameBnk.equals("1")) {
                tmpXElement.addChild(new XElement("BNKFLG", "Y"));
                tmpXElement.addChild(new XElement("EACBNK", ""));
                tmpXElement.addChild(new XElement("EACCTY", ""));
            } else {
                tmpXElement.addChild(new XElement("BNKFLG", "N"));
                tmpXElement.addChild(new XElement("EACBNK", p_req9108.singleDetail.getOppBankLocation()));
                tmpXElement.addChild(new XElement("EACCTY", p_req9108.singleDetail.getOppStandardArea()));
            }
            String trsDSP = "";
            boolean isUserPartnerAccount = getBankConfig().getValueAsBool("isUserPartnerAccount");
            if (isUserPartnerAccount) {
                trsDSP = getBankConfig().getMapValueByKey("contractInfoMapping", "partnerAccount");
            }
            tmpXElement.addChild(new XElement("TRSDSP", trsDSP));
            nodeAnalysis(p_req9108.singleDetail.srcXElement, tmpXElement, getCharset());
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if (!StringHelper.isNullOrEmpty(tmpRetCode) && !tmpRetCode.equals("-9")) {
                        tmpRetDetail.respCode = "0";
                        String tmpRSV50Z = tmpBkReader.getFirstText("/CMBSDKPGK/NTREQNBRY/RSV50Z");
                        if (tmpRSV50Z != null && tmpRSV50Z.length() > 0) {
//                            tmpRetDetail.transState = tmpRetCode + "+" + tmpRSV50Z;
//                            tmpRetDetail.payInfoCode = tmpRSV50Z;

                            // 当招行返回支付中时立刻发起支付状态查询
                            if ("BNK".equals(tmpRSV50Z)) {
                                long realSleepTime = getBankConfig().getValueAsInt("realSleepTime");
                                Thread.sleep(realSleepTime * 1000);

                                if (getBankConfig().getValueAsBool("UseNewQrySglRec")) {
                                    tmpBnkHeader.FUNNAM = "NTAGCINN";

                                    Calendar tmpBGNDAT = Calendar.getInstance();
                                    tmpBGNDAT.setTime(p_req9108.singleDetail.getPayDateTime());
                                    tmpBGNDAT.add(Calendar.DAY_OF_MONTH, -1);

                                    Calendar tmpENDDAT = Calendar.getInstance();
                                    tmpENDDAT.setTime(p_req9108.singleDetail.getPayDateTime());
                                    tmpENDDAT.add(Calendar.DAY_OF_MONTH, 1);

                                    xmlWriter = new XmlTextWriter();
                                    writeCommonHeader(xmlWriter, tmpBnkHeader);
                                    xmlWriter.writeStartElement("NTAGCINNY1");
                                    xmlWriter.writeElementString("BUSCOD", tmpBUSCOD);
                                    xmlWriter.writeElementString("BUSMOD", tmpBUSMOD);
                                    xmlWriter.writeElementString("BGNDAT", Format.Date8Format.format(tmpBGNDAT.getTime()));
                                    xmlWriter.writeElementString("ENDDAT", Format.Date8Format.format(tmpENDDAT.getTime()));
                                    xmlWriter.writeElementString("DATFLG", "A");
                                    xmlWriter.writeElementClosed("RSV50Z");
                                    xmlWriter.writeEndDocument();

                                    boolean isFinished = false;
                                    String tmpREQNBR = "";
                                    String tmpStrYURREF = "";
                                    String tmpStrBatchREQSTA = "";
                                    String tmpStrBatchRTNFLG = "";
                                    try {
                                        String[] tmpStrQryRet = sendToBank(xmlWriter.toXmlString());
                                        if (tmpStrQryRet[0].length() == 0) {
                                            tmpBkReader = loadBankRespXmlReader(tmpStrQryRet[1], tmpSbMsg);
                                            if (tmpBnkHeader != null) {
                                                tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                                                tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                                                if (tmpRetCode != null && tmpRetCode.equals("0")) {
                                                    boolean hasMatched = false;
                                                    while (tmpBkReader.read("/CMBSDKPGK/NTAGCINQZ")) {
                                                        String tmpStrC_REQSTA = tmpBkReader.readedXElement.getSingleText("C_REQSTA");
                                                        String tmpStrREQSTA = tmpBkReader.readedXElement.getSingleText("REQSTA");//业务请求状态
                                                        //业务处理结果//当REQSTA=FIN且RTNFLG=S需检查RSV62Z第一位是否为’P’，是表示部分成功，否则表示全部成功。
                                                        String tmpStrRTNFLG = tmpBkReader.readedXElement.getSingleText("RTNFLG");
                                                        String tmpStrSUCAMT = tmpBkReader.readedXElement.getSingleText("SUCAMT");
                                                        String tmpStrSUCNUM = tmpBkReader.readedXElement.getSingleText("SUCNUM");
                                                        String tmpStrERRDSP = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                                                        tmpStrYURREF = tmpBkReader.readedXElement.getSingleText("YURREF");
                                                        tmpREQNBR = tmpBkReader.readedXElement.getSingleText("REQNBR");
                                                        if (tmpStrYURREF != null && p_req9108.singleDetail.askNumber.equals(tmpStrYURREF)) {
                                                            hasMatched = true;
                                                            tmpStrBatchREQSTA = tmpStrREQSTA;
                                                            tmpStrBatchRTNFLG = tmpStrRTNFLG;
                                                            tmpRetDetail.reqSeqID = tmpStrYURREF;
                                                            if (tmpStrERRDSP != null && tmpStrERRDSP.length() > 32) {
                                                                tmpStrERRDSP = tmpStrERRDSP.substring(0, 33);
                                                            }
                                                            if (tmpStrREQSTA.equals("FIN") && tmpStrRTNFLG.equals("F") && StringHelper.isNullOrEmpty(tmpREQNBR)) {
                                                                float tmpSUCAMT = Float.parseFloat(tmpStrSUCAMT);
                                                                float tmpSUCNUM = Float.parseFloat(tmpStrSUCNUM);
                                                                if (tmpSUCAMT == 0 && tmpSUCNUM == 0) {
                                                                    tmpRetDetail.respCode = "0";
                                                                    tmpRetDetail.respInfo = tmpStrERRDSP;
                                                                    tmpRetDetail.transState = tmpStrREQSTA + "+" + tmpStrRTNFLG;
                                                                    tmpRetDetail.payInfoCode = tmpStrERRDSP;
                                                                    isFinished = true;
                                                                } else {
                                                                    tmpRetDetail.respCode = "-1";
                                                                    tmpRetDetail.respInfo = "成功笔数或成功金额不符合预期";
                                                                }
                                                            } else if (tmpStrREQSTA != null && !tmpStrREQSTA.equals("FIN")) {
                                                                tmpRetDetail.respCode = "0";
                                                                tmpRetDetail.respInfo = tmpStrC_REQSTA;
                                                                tmpRetDetail.transState = tmpStrREQSTA;
                                                                tmpRetDetail.payInfoCode = tmpStrREQSTA;
                                                                isFinished = true;
                                                            } else if (StringHelper.isNullOrEmpty(tmpStrREQSTA)) {
                                                                tmpRetDetail.respCode = "-1";
                                                                tmpRetDetail.respInfo = "批次的业务请求状态为空";
                                                            }
                                                        }
                                                    }
                                                    if (hasMatched == false) {
                                                        if (getBankConfig().getValueAsString("canBeFailed").contains(p_req9108.singleDetail.askNumber)) {
                                                            tmpRetDetail.respCode = "0";
                                                            tmpRetDetail.transState = "PaymentFailed";
                                                            tmpRetDetail.payInfoCode = "";
                                                            tmpRetDetail.respInfo = tmpRetMsg;
                                                            tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
                                                            isFinished = true;
                                                        } else {
                                                            tmpRetDetail.respCode = "-1";
                                                            tmpRetDetail.respInfo = "银行未返回该批次相关信息";
                                                        }
                                                    }
                                                } else {
                                                    tmpRetDetail.respCode = "-1";
                                                    tmpRetDetail.respInfo = tmpRetMsg;
                                                }
                                            }/* else {
                                                tmpRetDetail.respCode = "-1";
                                                tmpRetDetail.respInfo = tmpSbMsg.toString();
                                            }*/
                                        } else {
                                            tmpRetDetail.respCode = "-1";
                                            tmpRetDetail.respInfo = tmpStrQryRet[1];
                                        }
                                    } catch (Exception e) {
                                        tmpRetDetail.respCode = "-1";
                                        tmpRetDetail.respInfo = e.getMessage();
                                        e.printStackTrace();
                                    }

                                    if (isFinished || "-1".equals(tmpRetDetail.respCode)) {
                                        retAts.writeRetDetail(tmpRetDetail);
                                        return retAts;
                                    }

                                    //查明细
                                    tmpBnkHeader.FUNNAM = "GetAgentDetail";
                                    xmlWriter = new XmlTextWriter();
                                    writeCommonHeader(xmlWriter, tmpBnkHeader);
                                    xmlWriter.writeStartElement("SDKATDQYX");
                                    xmlWriter.writeElementString("REQNBR", tmpREQNBR);
                                    xmlWriter.writeEndDocument();

                                    try {
                                        tmpStrRet = sendToBank(xmlWriter.toXmlString());
                                        if (tmpStrRet[0].length() == 0) {
                                            tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                                            if (tmpBkReader != null) {
                                                tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                                                tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                                                if (tmpRetCode != null && tmpRetCode.equals("0")) {
                                                    if (tmpBkReader.read("/CMBSDKPGK/NTQATDQYZ")) {
                                                        tmpRetDetail.respCode = "0";
                                                        tmpRetDetail.transAmt = tmpBkReader.readedXElement.getSingleText("TRSAMT");
                                                        tmpRetDetail.reqSeqID = tmpStrYURREF;
                                                        tmpRetDetail.transState = tmpStrBatchREQSTA + "+" + tmpBkReader.readedXElement.getSingleText("STSCOD");
                                                        if (tmpStrBatchRTNFLG.equals("F") && tmpBkReader.readedXElement.getSingleText("STSCOD").equals("I")) {
                                                            tmpRetDetail.transState = tmpStrBatchREQSTA + "+" + tmpStrBatchRTNFLG + "+" + tmpBkReader.readedXElement.getSingleText("STSCOD");
                                                        }
                                                        tmpRetDetail.respInfo = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                                                        tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                                                        if (tmpRetDetail.payInfoCode != null && tmpRetDetail.payInfoCode.length() > 32) {
                                                            tmpRetDetail.payInfoCode = tmpRetDetail.payInfoCode.substring(0, 33);
                                                        }
                                                    }
                                                } else {
                                                    tmpRetDetail.respCode = "-1";
                                                    tmpRetDetail.respInfo = tmpRetMsg;
                                                }
                                            } else {
                                                tmpRetDetail.respCode = "-1";
                                                tmpRetDetail.respInfo = tmpSbMsg.toString();
                                            }
                                        } else {
                                            tmpRetDetail.respCode = "-1";
                                            tmpRetDetail.respInfo = tmpStrRet[1];
                                        }
                                    } catch (Exception e) {
                                        tmpRetDetail.respCode = "-1";
                                        tmpRetDetail.respInfo = e.getMessage();
                                        e.printStackTrace();
                                    }
                                    retAts.writeRetDetail(tmpRetDetail);
                                    return retAts;
                                }
                            }
                        } else {
                            tmpRetDetail.transState = tmpRetCode;
                            tmpRetDetail.payInfoCode = tmpRetCode;
                        }
                        tmpRetDetail.respInfo = tmpRetMsg;
                    } else if ("-9".equals(tmpRetCode)) {
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.transState = tmpRetCode + "+" + tmpRetMsg;
                        tmpRetDetail.payInfoCode = tmpRetMsg;
                        tmpRetDetail.respInfo = tmpRetMsg;
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpRetMsg;
                    }
                    if (tmpStrRet[1].contains("通讯故障") || tmpStrRet[1].contains("FBCM176")) {//FBCM176 通讯故障
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.transState = "Unknow";
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL) || tmpStrRet[0].equals(FailCode.E9981)) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = tmpStrRet[1];
                tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
                tmpRetDetail.transState = PaymentState.FAIL_Batch;
                tmpRetDetail.payInfoCode = tmpStrRet[0];
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[1];
            }

        } catch (Exception e) {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = e.toString();
            e.printStackTrace();
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
        String isSetSleep = getBankConfig().getValueAsString("useSleepGetQuery");
        if ("true".equals(isSetSleep.toLowerCase())) {
            int realSleepTime = getBankConfig().getValueAsInt("QuerySleepTime");
            if (realSleepTime > 0) {
                Date lastSleepGetQuery;
                String keyLastSleep = "lastSleepGetQuery9144";
                synchronized (bankFront.mutex9144) {
                    if (this.bankFront.customObjects.containsKey(keyLastSleep)) {
                        lastSleepGetQuery = (Date) bankFront.customObjects.get(keyLastSleep);
                        long diffMil = DateHelper.getDifferMilSecs(new Date(), lastSleepGetQuery);
                        long needSlpMil = realSleepTime * 1000;
                        long slpMil = needSlpMil - diffMil;
                        if (slpMil > 0) {
                            this.WriteBankLogLn("等待" + slpMil + "毫秒");
                            Thread.sleep(slpMil);
                        }
                        bankFront.putCustomObjects(keyLastSleep, new Date());
                    } else {
                        bankFront.putCustomObjects(keyLastSleep, new Date());
                    }
                }
            }
        }

        if (getBankConfig().getValueAsBool("UseNewQrySglRec")) {
            return d_9144_QryRealTimeRecNew(p_req9144);
        } else {
            return d_9144_QryRealTimeRecOld(p_req9144);
        }
    }

    public RetAtsSingle d_9144_QryRealTimeRecOld(ReqQrySingle p_req9144) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        //N03010:代发工资   N03020:代发   N03030:代扣
        String tmpBUSCOD = "N03030";
        CMB01Header tmpBnkHeader = new CMB01Header();
        tmpBnkHeader.FUNNAM = "GetAgentInfo";
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter, tmpBnkHeader);//写入通用的头部节点
        xmlWriter.writeStartElement("SDKATSQYX");
        xmlWriter.writeElementString("BUSCOD", tmpBUSCOD);
        Calendar tmpBGNDAT = Calendar.getInstance();
        tmpBGNDAT.setTime(p_req9144.getBgnDateTime());
        tmpBGNDAT.add(Calendar.DAY_OF_MONTH, -1);

        Calendar tmpENDDAT = Calendar.getInstance();
        tmpENDDAT.setTime(p_req9144.getBgnDateTime());
        tmpENDDAT.add(Calendar.DAY_OF_MONTH, 1);

        xmlWriter.writeElementString("BGNDAT", Format.Date8Format.format(tmpBGNDAT.getTime()));
        xmlWriter.writeElementString("ENDDAT", Format.Date8Format.format(tmpENDDAT.getTime()));

        xmlWriter.writeElementString("DATFLG", "A");
        xmlWriter.writeElementString("YURREF", p_req9144.askNumber);
        xmlWriter.writeElementClosed("OPRLGN");

        xmlWriter.writeEndDocument();
        boolean isFinished = false;
        String tmpREQNBR = "";
        String tmpStrBatchREQSTA = "";
        String tmpStrBatchRTNFLG = "";
        try {
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if (tmpRetCode != null && tmpRetCode.equals("0")) {
                        int tmpCountQYZ = tmpBkReader.countElement("/CMBSDKPGK/NTQATSQYZ");
                        if (tmpCountQYZ == 1) {
                            //String tmpStrC_RTNFLG = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/C_RTNFLG");
                            String tmpStrC_REQSTA = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/C_REQSTA");
                            String tmpStrREQSTA = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/REQSTA");//业务请求状态
                            //业务处理结果//当REQSTA=FIN且RTNFLG=S需检查RSV62Z第一位是否为’P’，是表示部分成功，否则表示全部成功。
                            String tmpStrRTNFLG = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/RTNFLG");
                            String tmpStrSUCAMT = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/SUCAMT");
                            String tmpStrSUCNUM = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/SUCNUM");
                            String tmpStrERRDSP = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/ERRDSP");
                            String tmpStrYURREF = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/YURREF");
                            if (tmpStrYURREF != null && p_req9144.askNumber.equals(tmpStrYURREF)) {
                                tmpREQNBR = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/REQNBR");
                                tmpStrBatchREQSTA = tmpStrREQSTA;
                                tmpStrBatchRTNFLG = tmpStrRTNFLG;
                                tmpRetDetail.reqSeqID = tmpStrYURREF;
                                if (tmpStrERRDSP != null && tmpStrERRDSP.length() > 32) {
                                    tmpStrERRDSP = tmpStrERRDSP.substring(0, 33);
                                }
                                if (tmpStrREQSTA.equals("FIN") && tmpStrRTNFLG.equals("F") && StringHelper.isNullOrEmpty(tmpREQNBR)) {
                                    float tmpSUCAMT = Float.parseFloat(tmpStrSUCAMT);
                                    float tmpSUCNUM = Float.parseFloat(tmpStrSUCNUM);
                                    //tmpStrSUCAMT.equals("0.00") && tmpStrSUCNUM.equals("00000")
                                    //查明细
                                    //AGN0025 无一笔入帐成功 查明细
                                    //if (!tmpStrERRDSP.startsWith("AGN0025"))
                                    //{
                                    //}
                                    if (tmpSUCAMT == 0 && tmpSUCNUM == 0) {
                                        tmpRetDetail.respCode = "0";
                                        tmpRetDetail.respInfo = tmpStrERRDSP;
                                        tmpRetDetail.transState = tmpStrREQSTA + "+" + tmpStrRTNFLG;
                                        tmpRetDetail.payInfoCode = tmpStrERRDSP;
                                        isFinished = true;
                                    } else {
                                        tmpRetDetail.respCode = "-1";
                                        tmpRetDetail.respInfo = "成功笔数或成功金额不符合预期";
                                    }
                                } else if (tmpStrREQSTA != null && !tmpStrREQSTA.equals("FIN")) {
                                    /*
                                     *业务请求状态
										AUT	等待审批
										NTE	终审完毕
										WCF	订单待确认（商务支付用）
										BNK	银行处理中
										FIN	完成
										ACK	等待确认(委托贷款用)
										APD 	待银行确认(国际业务用)
										OPR	数据接收中（代发）


										业务处理结果
										取值	含义	说明
										S	成功	银行支付成功
										F	失败	银行支付失败
										B	退票	银行支付被退票
										R	否决	企业审批否决
										D	过期	企业过期不审批
										C	撤消	企业撤销
										M	商户撤销订单	商务支付
										V	拒绝	委托贷款被借款方拒绝
                                     * */
                                    tmpRetDetail.respCode = "0";
                                    tmpRetDetail.respInfo = tmpStrC_REQSTA;
                                    tmpRetDetail.transState = tmpStrREQSTA;
                                    tmpRetDetail.payInfoCode = tmpStrREQSTA;
                                    isFinished = true;
                                } else if (StringHelper.isNullOrEmpty(tmpStrREQSTA)) {
                                    tmpRetDetail.respCode = "-1";
                                    tmpRetDetail.respInfo = "批次的业务请求状态为空";
                                }
                            } else {
                                tmpRetDetail.respCode = "-1";
                                tmpRetDetail.respInfo = "招行批号" + tmpStrYURREF + "与请求批号" + p_req9144.askNumber + "不相符";
                            }
                        } else if (tmpCountQYZ == 0) {
                            boolean tmpReadRoot = tmpBkReader.read("/CMBSDKPGK");
                            int tmpCountChild = -1;
                            if (tmpReadRoot) {
                                tmpCountChild = tmpBkReader.readedXElement.countChildren();
                            }
                            if (tmpRetCode.equals("0") && tmpStrRet[1].indexOf("NTQATSQYZ") < 0 && tmpReadRoot && tmpCountChild == 1) {
                                tmpRetDetail.respCode = "0";
                                tmpRetDetail.respInfo = "招行不存在该业务参考号";
                                tmpRetDetail.transState = PaymentState.FAIL_Batch;
                                tmpRetDetail.reqSeqID = p_req9144.askNumber;
                                tmpRetDetail.payInfoCode = "E1302";
                                isFinished = true;
                            } else {
                                tmpRetDetail.respCode = "-1";
                                tmpRetDetail.respInfo = "招行返回报文不符合预期";
                            }
                        } else {
                            tmpRetDetail.respCode = "-1";
                            tmpRetDetail.respInfo = "招行返回多个批次NTQATSQYZ节点";
                        }
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpRetMsg;
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }

        if (isFinished || tmpRetDetail.respCode.equals("-1")) {
            if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(p_req9144.askNumber)) {
                tmpRetDetail.reqSeqID = p_req9144.askNumber;
            }
            retAts.writeRetDetail(tmpRetDetail);
            return retAts;
        }

        if (!p_req9144.askNumber.equals(tmpRetDetail.reqSeqID)) {
            throw new Exception("取招行流水号出错，请求值为" + p_req9144.askNumber + "，取到值为" + tmpRetDetail.reqSeqID);
        }
        if (StringHelper.isNullOrEmpty(tmpREQNBR)) {
            throw new Exception("招行流水号为空");
        }

        //查明细
        tmpBnkHeader.FUNNAM = "GetAgentDetail";
        xmlWriter = null;
        xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter, tmpBnkHeader);//写入通用的头部节点
        xmlWriter.writeStartElement("SDKATDQYX");//
        xmlWriter.writeElementString("REQNBR", tmpREQNBR);
        xmlWriter.writeEndDocument();
        try {
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if (tmpRetCode != null && tmpRetCode.equals("0")) {
                        tmpRetDetail.respCode = "0";
                        if (tmpBkReader.read("/CMBSDKPGK/NTQATDQYZ")) {
                            tmpRetDetail = new RetAtsSglDetail();
                            tmpRetDetail.transAmt = tmpBkReader.readedXElement.getSingleText("TRSAMT");
                            tmpRetDetail.reqSeqID = tmpBkReader.readedXElement.getSingleText("TRSDSP");
                            tmpRetDetail.transState = tmpStrBatchREQSTA + "+" + tmpBkReader.readedXElement.getSingleText("STSCOD");
                            if (tmpStrBatchRTNFLG.equals("F") && tmpBkReader.readedXElement.getSingleText("STSCOD").equals("I")) {
                                tmpRetDetail.transState = tmpStrBatchREQSTA + "+" + tmpStrBatchRTNFLG + "+" + tmpBkReader.readedXElement.getSingleText("STSCOD");
                            }
                            tmpRetDetail.respInfo = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                            tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                            if (tmpRetDetail.payInfoCode != null && tmpRetDetail.payInfoCode.length() > 32) {
                                tmpRetDetail.payInfoCode = tmpRetDetail.payInfoCode.substring(0, 33);
                            }

                        }
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpRetMsg;
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(p_req9144.askNumber)) {
            tmpRetDetail.reqSeqID = p_req9144.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    public RetAtsSingle d_9144_QryRealTimeRecNew(ReqQrySingle p_req9144) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        //N03010:代发工资   N03020:代发   N03030:代扣
        String tmpBUSCOD = "N03030";
        CMB01Header tmpBnkHeader = new CMB01Header();
        tmpBnkHeader.FUNNAM = "NTAGCINN";
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter, tmpBnkHeader);//写入通用的头部节点
        xmlWriter.writeStartElement("NTAGCINNY1");
        xmlWriter.writeElementString("BUSCOD", tmpBUSCOD);
        String tmpBUSMOD = getBankConfig().getMapValueByKey("busmod" + tmpBUSCOD, p_req9144.officePurpose);
        xmlWriter.writeElementString("BUSMOD", tmpBUSMOD);
        Calendar tmpBGNDAT = Calendar.getInstance();
        tmpBGNDAT.setTime(p_req9144.getBgnDateTime());
        tmpBGNDAT.add(Calendar.DAY_OF_MONTH, -1);

        Calendar tmpENDDAT = Calendar.getInstance();
        tmpENDDAT.setTime(p_req9144.getBgnDateTime());
        tmpENDDAT.add(Calendar.DAY_OF_MONTH, 1);

        xmlWriter.writeElementString("BGNDAT", Format.Date8Format.format(tmpBGNDAT.getTime()));
        xmlWriter.writeElementString("ENDDAT", Format.Date8Format.format(tmpENDDAT.getTime()));

        xmlWriter.writeElementString("DATFLG", "A");
        xmlWriter.writeElementClosed("RSV50Z");

        xmlWriter.writeEndDocument();
        boolean isFinished = false;
        String tmpREQNBR = "";

        String tmpStrBatchREQSTA = "";
        String tmpStrBatchRTNFLG = "";
        try {
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if (tmpRetCode != null && tmpRetCode.equals("0")) {
                        boolean hasMatched = false;
                        while (tmpBkReader.read("/CMBSDKPGK/NTAGCINQZ")) {
                            //String tmpStrC_RTNFLG = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/C_RTNFLG");
                            String tmpStrC_REQSTA = tmpBkReader.readedXElement.getSingleText("C_REQSTA");
                            String tmpStrREQSTA = tmpBkReader.readedXElement.getSingleText("REQSTA");//业务请求状态
                            //业务处理结果//当REQSTA=FIN且RTNFLG=S需检查RSV62Z第一位是否为’P’，是表示部分成功，否则表示全部成功。
                            String tmpStrRTNFLG = tmpBkReader.readedXElement.getSingleText("RTNFLG");
                            String tmpStrSUCAMT = tmpBkReader.readedXElement.getSingleText("SUCAMT");
                            String tmpStrSUCNUM = tmpBkReader.readedXElement.getSingleText("SUCNUM");
                            String tmpStrERRDSP = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                            String tmpStrYURREF = tmpBkReader.readedXElement.getSingleText("YURREF");
                            if (tmpStrYURREF != null && p_req9144.askNumber.equals(tmpStrYURREF)) {
                                tmpREQNBR = tmpBkReader.readedXElement.getSingleText("REQNBR");
                                hasMatched = true;
                                tmpStrBatchREQSTA = tmpStrREQSTA;
                                tmpStrBatchRTNFLG = tmpStrRTNFLG;
                                tmpRetDetail.reqSeqID = tmpStrYURREF;
                                if (tmpStrERRDSP != null && tmpStrERRDSP.length() > 32) {
                                    tmpStrERRDSP = tmpStrERRDSP.substring(0, 33);
                                }
                                if (tmpStrREQSTA.equals("FIN") && tmpStrRTNFLG.equals("F") && StringHelper.isNullOrEmpty(tmpREQNBR)) {
                                    float tmpSUCAMT = Float.parseFloat(tmpStrSUCAMT);
                                    float tmpSUCNUM = Float.parseFloat(tmpStrSUCNUM);
                                    //tmpStrSUCAMT.equals("0.00") && tmpStrSUCNUM.equals("00000")
                                    //查明细
                                    //AGN0025 无一笔入帐成功 查明细
                                    //if (!tmpStrERRDSP.startsWith("AGN0025"))
                                    //{
                                    //}
                                    if (tmpSUCAMT == 0 && tmpSUCNUM == 0) {
                                        tmpRetDetail.respCode = "0";
                                        tmpRetDetail.respInfo = tmpStrERRDSP;
                                        tmpRetDetail.transState = tmpStrREQSTA + "+" + tmpStrRTNFLG;
                                        tmpRetDetail.payInfoCode = tmpStrERRDSP;
                                        isFinished = true;
                                    } else {
                                        tmpRetDetail.respCode = "-1";
                                        tmpRetDetail.respInfo = "成功笔数或成功金额不符合预期";
                                    }
                                } else if (tmpStrREQSTA != null && !tmpStrREQSTA.equals("FIN")) {
                                    /*
                                     *业务请求状态
										AUT	等待审批
										NTE	终审完毕
										WCF	订单待确认（商务支付用）
										BNK	银行处理中
										FIN	完成
										ACK	等待确认(委托贷款用)
										APD 	待银行确认(国际业务用)
										OPR	数据接收中（代发）


										业务处理结果
										取值	含义	说明
										S	成功	银行支付成功
										F	失败	银行支付失败
										B	退票	银行支付被退票
										R	否决	企业审批否决
										D	过期	企业过期不审批
										C	撤消	企业撤销
										M	商户撤销订单	商务支付
										V	拒绝	委托贷款被借款方拒绝
                                     * */
                                    tmpRetDetail.respCode = "0";
                                    tmpRetDetail.respInfo = tmpStrC_REQSTA;
                                    tmpRetDetail.transState = tmpStrREQSTA;
                                    tmpRetDetail.payInfoCode = tmpStrREQSTA;
                                    isFinished = true;
                                } else if (StringHelper.isNullOrEmpty(tmpStrREQSTA)) {
                                    tmpRetDetail.respCode = "-1";
                                    tmpRetDetail.respInfo = "批次的业务请求状态为空";
                                }
                                break;
                            }
                        }
                        if (hasMatched == false) {
                            if (getBankConfig().getValueAsString("canBeFailed").contains(p_req9144.askNumber)) {
                                tmpRetDetail.respCode = "0";
                                tmpRetDetail.transState = "PaymentFailed";
                                tmpRetDetail.payInfoCode = "";
                                tmpRetDetail.respInfo = tmpRetMsg;
                                tmpRetDetail.reqSeqID = p_req9144.askNumber;
                                isFinished = true;
                            } else {
                                tmpRetDetail.respCode = "-1";
                                tmpRetDetail.respInfo = "银行未返回该批次相关信息";
                            }
                        }
                    } else if (getBankConfig().getValueAsString("canBeFailed").contains(p_req9144.askNumber) && getBankConfig().getValueAsString("canBeFailedMsg").contains(tmpRetMsg)) {
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.transState = "PaymentFailed";
                        tmpRetDetail.payInfoCode = "";
                        tmpRetDetail.respInfo = tmpRetMsg;
                        tmpRetDetail.reqSeqID = p_req9144.askNumber;
                        isFinished = true;
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpRetMsg;
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }

        if (isFinished || "-1".equals(tmpRetDetail.respCode)) {
            if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(p_req9144.askNumber)) {
                tmpRetDetail.reqSeqID = p_req9144.askNumber;
            }
            retAts.writeRetDetail(tmpRetDetail);
            return retAts;
        }

        if (!p_req9144.askNumber.equals(tmpRetDetail.reqSeqID)) {
            throw new Exception("取招行流水号出错，请求值为" + p_req9144.askNumber + "，取到值为" + tmpRetDetail.reqSeqID);
        }
        if (StringHelper.isNullOrEmpty(tmpREQNBR)) {
            throw new Exception("招行流水号为空");
        }

        //查明细
        tmpBnkHeader.FUNNAM = "GetAgentDetail";
        xmlWriter = null;
        xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter, tmpBnkHeader);//写入通用的头部节点
        xmlWriter.writeStartElement("SDKATDQYX");//
        xmlWriter.writeElementString("REQNBR", tmpREQNBR);
        xmlWriter.writeEndDocument();
        try {
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if (tmpRetCode != null && tmpRetCode.equals("0")) {
                        if (tmpBkReader.read("/CMBSDKPGK/NTQATDQYZ")) {
                            String tmpReqSeqID = tmpRetDetail.reqSeqID;
                            tmpRetDetail = new RetAtsSglDetail();
                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.transAmt = tmpBkReader.readedXElement.getSingleText("TRSAMT");
                            tmpRetDetail.reqSeqID = tmpReqSeqID;//tmpBkReader.readedXElement.getSingleText("TRSDSP");
                            tmpRetDetail.transState = tmpStrBatchREQSTA + "+" + tmpBkReader.readedXElement.getSingleText("STSCOD");
                            String bkSTSCOD = tmpBkReader.readedXElement.getSingleText("STSCOD");
                            if ("F".equals(tmpStrBatchRTNFLG) && "I".equals(bkSTSCOD)) {
                                tmpRetDetail.transState = tmpStrBatchREQSTA + "+" + tmpStrBatchRTNFLG + "+" + bkSTSCOD;
                            } else if ("F".equals(tmpStrBatchRTNFLG) && "S".equals(bkSTSCOD)) {
                                tmpRetDetail.transState = tmpStrBatchREQSTA + "+" + tmpStrBatchRTNFLG + "+" + bkSTSCOD;
                            } else if ("S".equals(tmpStrBatchRTNFLG) && ("F".equals(bkSTSCOD) || "E".equals(bkSTSCOD))) {
                                tmpRetDetail.transState = tmpStrBatchREQSTA + "+" + tmpStrBatchRTNFLG + "+" + bkSTSCOD;
                            }
                            tmpRetDetail.respInfo = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                            tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("ERRDSP");
                            if (tmpRetDetail.payInfoCode != null && tmpRetDetail.payInfoCode.length() > 32) {
                                tmpRetDetail.payInfoCode = tmpRetDetail.payInfoCode.substring(0, 33);
                            }

                        }
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpRetMsg;
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(tmpRetDetail.respCode) && StringHelper.isNullOrEmpty(p_req9144.askNumber)) {
            tmpRetDetail.reqSeqID = p_req9144.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }
}
